package tushare

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"tushare/conf"
	"tushare/model"
	"tushare/model/tushare"
)

type requestRaw struct {
	ApiName string        `json:"api_name"`
	Token   string        `json:"token"`
	Fields  string        `json:"fields"`
	Params  requestParams `json:"params"`
}

type requestParams struct {
	TsCode    string `json:"ts_code"`
	StartDate string `json:"start_date"`
	EndDate   string `json:"end_date"`
}

type resposeMoneyFlow struct {
	RequestId string               `json:"request_id"`
	Code      int                  `json:"code"`
	Data      moneyFlowResposeData `json:"data"`
}

type moneyFlowResposeData struct {
	Items [][]interface{} `json:"items"`
}

func CheckMoneyflow() {
	stocks := model.StockList()
	for _, v := range stocks {
		mf := tushare.CheckMoneyFlow(v.TsCode, "20211221")
		if mf.Id == 0 {
			fmt.Println("空")
			moneyFlowCreate(v.TsCode, "20211221", "20211221")
		} else {
			fmt.Println(v.TsCode)
		}
	}
}

//拉取个股资金流向
func Moneyflow(startDate, endDate string) {
	moneyFlowCreate("", startDate, endDate)
}

func moneyFlowCreate(tsCode, startDate, endDate string) {
	rw := requestRaw{}
	rw.ApiName = "moneyflow"
	rw.Token = conf.GetToken()
	rw.Fields = "ts_code,trade_date,buy_sm_vol,buy_sm_amount,sell_sm_vol,sell_sm_amount,buy_md_vol,buy_md_amount,sell_md_vol,sell_md_amount,buy_lg_vol,buy_lg_amount,sell_lg_vol,sell_lg_amount,buy_elg_vol,buy_elg_amount,sell_elg_vol,sell_elg_amount,net_mf_vol,net_mf_amount"
	rw.Params.TsCode = tsCode
	rw.Params.StartDate = startDate
	rw.Params.EndDate = endDate

	rwJson, _ := json.Marshal(rw)

	resp, _ := http.Post("http://api.waditu.com", "application/json", bytes.NewReader(rwJson))
	body, _ := ioutil.ReadAll(resp.Body)

	jsonStrByte := []byte(body)
	decodeData := resposeMoneyFlow{}
	json.Unmarshal(jsonStrByte, &decodeData)

	for _, v := range decodeData.Data.Items {
		mf := tushare.MoneyFlowCreateStruct{}
		mf.TsCode = v[0].(string)
		mf.TradeDate = v[1].(string)

		mf.BuySmVol = interfaceNilToZero(v[2])
		mf.BuySmAmount = interfaceNilToZero(v[3])
		mf.SellSmVol = interfaceNilToZero(v[4])
		mf.SellSmAmount = interfaceNilToZero(v[5])
		mf.BuyMdVol = interfaceNilToZero(v[6])
		mf.BuyMdAmount = interfaceNilToZero(v[7])
		mf.SellMdVol = interfaceNilToZero(v[8])
		mf.SellMdAmount = interfaceNilToZero(v[9])
		mf.BuyLgVol = interfaceNilToZero(v[10])
		mf.BuyLgAmount = interfaceNilToZero(v[11])
		mf.SellLgVol = interfaceNilToZero(v[12])
		mf.SellLgAmount = interfaceNilToZero(v[13])
		mf.BuyElgVol = interfaceNilToZero(v[14])
		mf.BuyElgAmount = interfaceNilToZero(v[15])
		mf.SellElgVol = interfaceNilToZero(v[16])
		mf.SellElgAmount = interfaceNilToZero(v[17])
		mf.NetMfVol = interfaceNilToZero(v[18])
		mf.NetMfAmount = interfaceNilToZero(v[19])

		tushare.MoneyFlowCreate(mf)
	}
}

func interfaceNilToZero(n interface{}) float64 {
	var val interface{} = nil
	if val == n {
		return 0
	} else {
		return n.(float64)
	}
	return 0
}
